package pers.li.controller.goods;

import pers.li.model.VO.CarVO;
import pers.li.utils.JsonUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@WebServlet("/goods/remCart.action")
public class RemoveCartController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader br = req.getReader();
        String line = null;
        String body = null;
        while ((line = br.readLine()) != null) {
            body = line;
        }
        assert body != null;
        String trId = JsonUtil.parseObject(body, String.class);

        List<CarVO> carVOList = (List<CarVO>) req.getSession().getAttribute("car");
        List<CarVO> collect = carVOList.stream().filter(cv -> !cv.getTrId().equals(trId)).collect(Collectors.toList());
        /*for (int i = 0; i < carVOList.size(); i++) {
            if (carVOList.get(i).getGoodsId() == goodId) {
                carVOList.remove(i);
                break;
            }
        }*/
        req.getSession().setAttribute("car",collect);
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        Map<String,Object> res = new HashMap<>();
        res.put("success",true);
        writer.print(JsonUtil.toJsonString(res));
        writer.flush();
        writer.close();
    }
}
